package scraper

import (
	"context"
	"database/sql"

	"github.com/prometheus/client_golang/prometheus"
	"go.uber.org/zap"
)

var cpuSQL = `SELECT CPU_USER_RATE,CPU_SYSTEM_RATE,CPU_IDLE_RATE FROM V$SYSTEMINFO`

var scraperCPUUserRateDesc = prometheus.NewDesc(
	prometheus.BuildFQName(Namespace, Exporter, "collect_cpu_user_utilization"),
	"Collect CPU User utilization",
	[]string{"collector"},
	nil,
)
var scraperCPUSystemRateDesc = prometheus.NewDesc(
	prometheus.BuildFQName(Namespace, Exporter, "collect_cpu_system_utilization"),
	"Collect CPU System utilization",
	[]string{"collector"},
	nil,
)
var scraperCPUIdleRateDesc = prometheus.NewDesc(
	prometheus.BuildFQName(Namespace, Exporter, "collect_cpu_idle_utilization"),
	"Collect CPU Idle utilization",
	[]string{"collector"},
	nil,
)

type ScrapeCPU struct{}

func (ScrapeCPU) Name() string {
	return "cpu_utilization"
}

func (ScrapeCPU) Usage() string {
	return "Current CPU Utilization of kingbaseDB"
}

func (ScrapeCPU) Scraper(ctx context.Context, db *sql.DB, ch chan<- prometheus.Metric, logger *zap.Logger) error {
	user, system, idle := 0.0, 0.0, 0.0
	err := db.QueryRow(cpuSQL).Scan(&user, &system, &idle)
	if err != nil {
		logger.Sugar().Errorf("Failed to scrape cpu info: %v", err)
		return err
	}
	ch <- prometheus.MustNewConstMetric(
		scraperCPUUserRateDesc, prometheus.GaugeValue, user, "connection",
	)
	ch <- prometheus.MustNewConstMetric(
		scraperCPUSystemRateDesc, prometheus.GaugeValue, system, "connection",
	)
	ch <- prometheus.MustNewConstMetric(
		scraperCPUIdleRateDesc, prometheus.GaugeValue, idle, "connection",
	)
	return nil
}

var _ DBScraper = (*ScrapeCPU)(nil)
